package com.etymgiko.spaceshipshop.web;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import com.etymgiko.spaceshipshop.service.SpaceShipManager;
import com.etymgiko.spaceshipshop.model.SpaceShip;
import com.etymgiko.spaceshipshop.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Sells ship.
 *
 * @author Ivan Holub
 */
public class SellShipAction extends Action {
    private SpaceShipManager spaceShipManager;

    public void setSpaceShipManager(SpaceShipManager spaceShipManager) {
        this.spaceShipManager = spaceShipManager;
    }

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

        IdForm idForm = (IdForm) form;

        User user = (User) request.getSession().getAttribute("user");

        Long id = idForm.getId();

        SpaceShip ship = spaceShipManager.getSpaceShip(id);
        User owner = ship.getOwner();
        if (owner == null || !user.getId().equals(owner.getId())) {
            return mapping.findForward("error");    
        }
        ship.setOwner(null);

        spaceShipManager.saveSpaceShip(ship);

        return mapping.findForward("success");
    }

}